defmodule SockWorkstation.NodeManagerGen do
  use GenServer

  @name __MODULE__
  @nodemphx :"mediaphx@72-j.cn"
  # 客户端接口
  def start_link(nodes \\ []) do
    GenServer.start_link(@name, nodes, name: @name)
  end

  def connect(node) do
    GenServer.cast(@name, {:connect, node})
  end

  def disconnect(node) do
    GenServer.cast(@name, {:disconnect, node})
  end

  def list_nodes() do
    GenServer.call(@name, :list_nodes)
  end


  # def get_sessid(macaddr) do
  #   GenServer.call(@name, {:get_sessid, macaddr})
  # end

  # def get_userid(sess_id) do
  #   GenServer.call(@name, {:get_userid, sess_id})
  # end

  # def add_deviceid(device_id) do
  #   GenServer.cast(@name, {:add_deviceid, device_id})
  # end
  # 服务器回调
  @impl true
  def init(nodes) do
    connected_nodes =
      Enum.filter(nodes, fn node ->
        case Node.connect(node) do
          true ->
            IO.puts("Connected to #{node}")
            true
          false ->
            IO.puts("Failed to connect to #{node}")
            false
        end
      end)

    {:ok, connected_nodes}
  end
  
  @impl true
  def handle_cast({:connect, node}, nodes) do
    # 尝试连接到新节点
    if Node.connect(node) do
      IO.puts("已连接到节点 #{inspect(node)}")
      {:noreply, [node | nodes]}
    else
      IO.puts("无法连接到节点 #{inspect(node)}")
      {:noreply, nodes}
    end
  end

  def handle_cast({:disconnect, node}, nodes) do
    # 断开与节点的连接
    Node.disconnect(node)
    IO.puts("已断开与节点 #{inspect(node)} 的连接")
    {:noreply, List.delete(nodes, node)}
  end
  # def handle_cast({:add_deviceid, device_id}, state) do
  #   # node=:"ab@72-j.cn"

  #   if @nodemphx in state do
  #     case  :rpc.call(@nodemphx, Panda.IotAI.AuthcodeSession, :create_authcode, [%{macaddr: device_id}]) do
  #       {:ok, result} ->
  #         IO.puts("远程调用结果: #{result}")

  #       {:error,_ , map} -> IO.puts("远程调用: #{inspect(map)}")
  #         _ -> IO.puts("远程调用失败")
  #       end
  #     end
  #     {:noreply, state}
  # end

  @impl true
  def handle_call(:list_nodes, _from, nodes) do
    # 返回当前连接的节点列表
    {:reply, nodes, nodes}
  end



  def handle_call({:get_sessid, macaddr},_from, state) do

    # macaddr=String.replace(device_id, ":", "-")
    resp=:rpc.call(@nodemphx, Panda.IotAI.Queries, :macaddr_to_authcodeid, [macaddr])

     {:reply,resp, state}
  end

  def handle_call({:get_userid, sess_id}, _from, state) do
    resp=:rpc.call(@nodemphx, Panda.IotAI.Queries, :authcode_to_userid, [sess_id])
    {:reply, resp, state}
  end
end

    # case :rpc.call(@nodemphx, Panda.IotAI.Queries, :macaddr_to_authcodeid, [macaddr]) do
    #   {:ok, result} ->
    #     IO.puts("远程调用结果: #{result}")

    #   {:error,_ , map} -> IO.puts("远程调用: #{inspect(map)}")
    #   {:error, reason} -> IO.puts("远程调用失败: #{reason}")

    #     _ -> IO.puts("远程调用失败")
    #   end
